<div class="subhead">
  <div class="container mx-auto">
    <h5>~/logs/<%= link @source.name, to: Routes.source_path(@conn, :show, @source) |> Utils.with_team_param(@team), class:  "text-primary" %>/edit</h5>
    <div class="log-settings">
      <ul>
        <li>
          <%= link to: Routes.source_live_path(@conn, LogflareWeb.Sources.RulesLive, @source.id) |> Utils.with_team_param(@team) do %>
            <i class="fas fa-code-branch"></i><span class="hide-on-mobile"> rules</span>
        <% end %>
        </li>
        <li><a href="mailto:support@logflare.app?Subject=Logflare%20Help" target="_top"><i
              class="fas fa-question-circle"></i> <span class="hide-on-mobile">help</a></span></li>
      </ul>
    </div>

  </div>
</div>
<div class="content container mx-auto">
  <%= section_header("Source Name") %>
  <p>For example, <code>YourApp</code> would be good for all logs from your app. <code>YourApp.bots</code> would be a
    good place to keep all bot logs. Route logs with LQL rules using
    <%= link "rules", to: Routes.source_live_path(@conn, LogflareWeb.Sources.RulesLive, @source.id) |> Utils.with_team_param(@team) %>.</p>
  <%= form_for @changeset, Routes.source_path(@conn, :update, @source), fn a -> %>
  <div class="form-group">
    <%= text_input a, :name, placeholder: "YourApp.SourceName", class: "form-control form-control-margin" %>
    <%= error_tag a, :name %>
  </div>
  <%= submit "Update name", class: "btn btn-primary form-button" %>
  <% end %>

  <%= section_header("Service Group") %>
  <p>Organize your sources into a common business domain service group.</p>
  <%= form_for @changeset, Routes.source_path(@conn, :update, @source), fn a -> %>
  <div class="form-group">
    <%= text_input a, :service_name, placeholder: "Payments", class: "form-control form-control-margin" %>
    <%= error_tag a, :service_name %>
  </div>
  <%= submit "Update service group", class: "btn btn-primary form-button" %>
  <% end %>

  <%= section_header("Alert Frequency") %>
  <p>How often do you want to receive alerts?</p>
  <div class="form-group">
    <%= form_for @changeset, Routes.source_path(@conn, :update, @source), fn h -> %>
    <%= select h, :notifications_every, @notifications_opts, prompt: "Frequency", class: "form-control form-control-margin"  %>
    <%= error_tag h, :notifications_every %>
  </div>
  <%= submit "Update alert frequency", class: "btn btn-primary form-button" %>
  <% end %>

  <%= section_header("Email Alerts") %>
  <p>Send emails when this source gets new events. Add email addresses below. Sometimes sources can get a lot of events
    quickly. At most you will get one email per minute.</p>
  <%= form_for @changeset, Routes.source_path(@conn, :update, @source), fn b -> %>
  <div class="form-group">
    <%= inputs_for b, :notifications, fn bn -> %>
    <%= text_input bn, :other_email_notifications, placeholder: "her@friend.com, him@company.com", class: "form-control form-control-margin" %>
    <%= error_tag bn, :other_email_notifications %>
    <small class="form-text text-muted">
      Comma separated list of emails please.
    </small>
    <div class="form-control-margin">
      <%= label bn, :user_email_notifications, "Send email alerts to the account owner ", class: "" %>
      <%= if is_nil(@user.email_preferred) do %>
      <%= link " (add a preferred email)", to: Routes.user_path(@conn, :edit), class: "label-padding"%>
      <% else %>
      <%= link " (#{@user.email_preferred})", to: Routes.user_path(@conn, :edit), class: "label-padding" %>
      <% end %>
      <%= checkbox bn, :user_email_notifications %>
      <%= error_tag bn, :user_email_notifications %>
    </div>
    <%= label bn, :team_user_ids_for_email, "Select some team members to alert", class: "label-padding" %></br>
    <%= multiple_select bn, :team_user_ids_for_email, Enum.map(@team.team_users, fn x -> {"#{x.name || x.email} (#{x.email})", x.id} end), selected: @source.notifications.team_user_ids_for_email, class: "form-control form-control-margin selectpicker", data: [width: "65%"] %>
    <small class="form-text text-muted">
      Reset email preferences to clear this list.
    </small>
    <% end %>
  </div>
  <%= submit "Update email preferences", class: "btn btn-primary form-button" %>
  <% end %>
  <%= form_for @changeset, Routes.source_path(@conn, :update, @source), fn clear_b -> %>
  <%= inputs_for clear_b, :notifications, fn bn -> %>
  <%= hidden_input(bn, :user_email_notifications, value: "false") %>
  <%= hidden_input(bn, :team_user_ids_for_email, value: []) %>
  <%= hidden_input(bn, :other_email_notifications, value: "") %>
  <% end %>
  <%= submit "Reset", class: "btn btn-sm btn-secondary form-button" %>
  <% end %>

  <%= section_header("SMS Alerts") %>
  <p>Get text message alerts when a source gets new events. Sometimes sources can get a lot of events quickly. At most
    you will get one text message per minute.</p>
  <%= if @plan.name != "Free" do %>
    <%= form_for @changeset, Routes.source_path(@conn, :update, @source), fn c -> %>
      <div class="form-group">
        <div class="form-control-margin">
          <%= inputs_for c, :notifications, fn cn -> %>
          <%= label cn, :user_text_notifications, "Send SMS alerts to the account owner", class: "" %>
          <%= if is_nil(@user.phone) do %>
          <%= link " (add a phone number)", to: Routes.user_path(@conn, :edit), class: "label-padding" %>
          <% else %>
          <%= link " (#{@user.phone})", to: Routes.user_path(@conn, :edit), class: "label-padding" %>
          <% end %>
          <%= checkbox cn, :user_text_notifications %>
          <%= error_tag cn, :user_text_notifications %>
        </div>
        <%= label cn, :team_user_ids_for_sms, "Select some team members to alert (team members without phone numbers are not listed)", class: "label-padding" %>
        <%= multiple_select cn, :team_user_ids_for_sms, Enum.filter(@team.team_users, &(&1.phone)) |> Enum.map(fn x -> {"#{x.name || x.email} (#{x.phone})", x.id} end), selected: @source.notifications.team_user_ids_for_sms, class: "form-control form-control-margin selectpicker", data: [width: "65%"] %>
        <small class="form-text text-muted">
          Reset SMS preferences to clear this list.
        </small>
        <% end %>
      </div>
      <%= submit "Update SMS preferences", class: "btn btn-primary form-button" %>
    <% end %>
    <% else %>
    <p>SMS alerts are not available with the Free plan.</p>
  <% end %>
  <%= form_for @changeset, Routes.source_path(@conn, :update, @source), fn clear_c -> %>
  <%= inputs_for clear_c, :notifications, fn cn -> %>
  <%= hidden_input(cn, :user_text_notifications, value: "false") %>
  <%= hidden_input(cn, :team_user_ids_for_sms, value: []) %>
  <% end %>
  <%= submit "Reset", class: "btn btn-sm btn-secondary form-button" %>
  <% end %>
  <%= section_header("Slack Alerts") %>
  <p>Get Logflare notifications in your Slack channels! Separate from signing in with Slack. You can send alerts to any
    Slack channel from any Logflare source.</p>
  <div class="form-button">
    <a
      href="https://slack.com/oauth/v2/authorize?client_id=<%= Application.get_env(:ueberauth, Ueberauth.Strategy.SlackV2.OAuth)[:client_id] %>&scope=incoming-webhook&install_redirect=update-to-granular-scopes&redirect_uri=<%= LogflareWeb.Endpoint.url() <> "/auth/slack/callback" %>&state=<%= Jason.encode!(%{"action" => "save_hook_url", "source" => @source}) %>"><img
        alt="Add to Slack" height="40" width="139" src="https://platform.slack-edge.com/img/add_to_slack.png"
        srcset="https://platform.slack-edge.com/img/add_to_slack.png 1x, https://platform.slack-edge.com/img/add_to_slack@2x.png 2x"></a>
  </div>
  <%= if @source.slack_hook_url do %>
  <%= link "Test Slack webhook", to: Routes.source_path(@conn, :test_slack_hook, @source), class: "btn btn-primary form-button", role: "button" %>
  <%= link "Delete Slack webhook", to: Routes.source_path(@conn, :delete_slack_hook, @source), class: "btn btn-sm btn-danger form-button", role: "button" %>
  <% end %>

  <%= section_header("Schema Change Alerts") %>
  <p>We automatically update your source schema based on the incoming metadata payload. Get an email when the source
    schema is updated.</p>
  <%= form_for @changeset, Routes.source_path(@conn, :update, @source), fn b -> %>
  <div class="form-group">
    <%= inputs_for b, :notifications, fn bn -> %>

    <div class="form-control-margin">
      <%= label bn, :user_schema_update_notifications, "Send schema change alerts to the account owner ", class: "" %>
      <%= if is_nil(@user.email_preferred) do %>
      <%= link " (add a preferred email)", to: Routes.user_path(@conn, :edit), class: "label-padding"%>
      <% else %>
      <%= link " (#{@user.email_preferred})", to: Routes.user_path(@conn, :edit), class: "label-padding" %>
      <% end %>
      <%= checkbox bn, :user_schema_update_notifications %>
      <%= error_tag bn, :user_schema_update_notifications %>
    </div>
    <%= label bn, :team_user_ids_for_schema_updates, "Select some team members to alert", class: "label-padding" %></br>
    <%= multiple_select bn, :team_user_ids_for_schema_updates, Enum.map(@team.team_users, fn x -> {"#{x.name || x.email} (#{x.email})", x.id} end), selected: @source.notifications.team_user_ids_for_schema_updates, class: "form-control form-control-margin selectpicker", data: [width: "65%"] %>
    <small class="form-text text-muted">
      Reset preferences to clear this list.
    </small>
    <% end %>
  </div>
  <%= submit "Update schema change notifications", class: "btn btn-primary form-button" %>
  <% end %>
  <%= form_for @changeset, Routes.source_path(@conn, :update, @source), fn clear_b -> %>
  <%= inputs_for clear_b, :notifications, fn bn -> %>
  <%= hidden_input(bn, :user_schema_update_notifications, value: "true") %>
  <%= hidden_input(bn, :team_user_ids_for_schema_updates, value: []) %>
  <%= hidden_input(bn, :other_email_notifications, value: "") %>
  <% end %>
  <%= submit "Reset", class: "btn btn-sm btn-secondary form-button" %>
  <% end %>

  <%= section_header("Webhook Alerts") %>
  <p>We recommend setting up <%= link "RequestBin", to: "https://requestbin.com/", target: "_blank" %> to see what our
    payloads look like. Once a webhook url is saved here you can send a test request to it.</p>
  <p><i class="fab fa-discord"></i> Payloads are automagically compatible with Discord webhook urls!</p>
  <%= form_for @changeset, Routes.source_path(@conn, :update, @source), fn f -> %>
  <div class="form-group">
    <%= url_input f, :webhook_notification_url, placeholder: "https://mydomain.com/webhooks/logflare", class: "form-control form-control-margin" %>
    <small class="form-text text-muted">
      This endpoint should accept POST requests with a JSON body.
    </small>
    <%= error_tag f, :webhook_notification_url %>
  </div>
  <%= submit "Update webhook preferences", class: "btn btn-primary form-button" %>
  <% end %>
  <%= if @source.webhook_notification_url do %>
  <%= link "Test webhook", to: Routes.source_path(@conn, :test_alerts, @source), class: "btn btn-primary form-button", role: "button" %>
  <% end %>

  <%= section_header("Public Access") %>
  <p>Public paths let you share your logs with other people without having to give them a login. Generate a public token
    and this source will be accessible by anyone with this url. Regenerate a public path if needed.</p>
  <%= if @source.public_token != nil do %>
  <div>
    <code><%= Routes.source_url(@conn, :public, @source.public_token) %></code>
    <button class="btn btn-secondary btn-sm" id="copy-path" data-clipboard-text="<%= Routes.source_url(@conn, :public, @source.public_token) %>">Copy path</button>
  </div>
  <% end %>
  <%= form_for @changeset, Routes.source_path(@conn, :update, @source), fn d -> %>
  <div class="form-group">
    <%= hidden_input d, :public_token, value: :crypto.strong_rand_bytes(12) |> Base.url_encode64, class: "form-control form-control-margin" %>
    <%= error_tag d, :public_token %>
  </div>
  <%= submit "Generate path", class: "btn btn-primary form-button" %>
  <% end %>

  <%= section_header("Schema Lock") %>
  <p>Lock this source schema to keep it from updating automatically. Any new fields encountered during ingest will be ignored.
  </p>
  <%= form_for @changeset, ~p"/sources/#{@source}/#schema-lock", [method: :patch], fn f -> %>
    <%= hidden_input f, :lock_schema, value: !@source.lock_schema %>
    <%= submit "#{if @source.lock_schema, do: "Unlock", else: "Lock"} schema", class: "btn btn-primary form-button" %>
  <% end %>

  <%= section_header("Schema Validation") %>
  <p>Disable schema validation on ingest. Use this for high volume sources. Typically schema validation should be disabled for sources seeing >1,000 log events per second.
  </p>
  <%= form_for @changeset, ~p"/sources/#{@source}/#schema-validation", [method: :patch], fn f -> %>
    <%= hidden_input f, :validate_schema, value: !@source.validate_schema %>
    <%= submit "#{if @source.validate_schema, do: "Disable", else: "Enable"} schema validation", class: "btn btn-primary form-button" %>
  <% end %>


  <hr/>
  <h3>Pipeline Rules</h3>

  <%= section_header("Drop Log Events") %>
  <p>Use an LQL statement to drop log events on ingest.</p>
  <%= form_for @changeset, Routes.source_path(@conn, :update, @source), fn drop -> %>
  <div class="form-group">
    <%= text_input drop, :drop_lql_string, placeholder: "", class: "form-control form-control-margin" %>
    <%= error_tag drop, :drop_lql_string %>
  </div>
  <%= submit "Update LQL", class: "btn btn-primary form-button" %>
  <% end %>

  <%= section_header("Custom Event Message") %>
  <p>Comma separated list of metadata keys to customize the log event message. Use <code>message</code> to target the default log event message. Use JSONpath queries to target more complex nested data structures. The root (<code>$.</code>) is implied here.</p>
  <%= form_for @changeset, Routes.source_path(@conn, :update, @source), fn aa -> %>
  <div class="form-group">
    <%= text_input aa, :custom_event_message_keys, placeholder: "metadata.field.key, metadata.field.another_key", class: "form-control form-control-margin" %>
    <%= error_tag aa, :custom_event_message_keys %>
    <small class="form-text text-muted">
      Key values will be concatenated with a pipe ( | ).
    </small>
  </div>

  <%= submit "Update keys", class: "btn btn-primary form-button" %>
  <% end %>


  <%= section_header("Copy fields") %>
  <p>
    Copy fields to different paths at ingestion.  Rules are executed sequentailly. Invalid rules are ignored.
  </p>
  <%= form_for @changeset, Routes.source_path(@conn, :update, @source), fn e -> %>
    <div class="form-group">
      <%= textarea e, :transform_copy_fields, placeholder: "metadata.my_field:my.destination.path", class: "form-control form-control-margin tw-h-[120px]" %>
      <%= error_tag e, :transform_copy_fields %>
      <small class="form-text text-muted">
        Separate each rule with a new line. Use the pattern <code>from.field:to.other.field</code> to specify the path to copy a field.
      </small>
    </div>
    <%= submit "Update field copying rules", class: "btn btn-primary form-button" %>
  <% end %>
  <hr/>

  <%= section_header("Backend TTL") %>
  <%= if @conn.assigns.user.billing_enabled do %>
    <p>Set how long to keep data in your backend.</p>
    <%= form_for @changeset, Routes.source_path(@conn, :update, @source), fn e -> %>
    <div class="form-group">
      <%= text_input e, :retention_days, placeholder: "3", class: "form-control form-control-margin" %>
      <%= error_tag e, :retention_days %>
      <small class="form-text text-muted">
        Days to keep data.
      </small>
    </div>
    <%= submit "Update backend settings", class: "btn btn-primary form-button" %>
    <% end %>
  <% else %>
    <p>Add a Google Cloud Platform project ID to get started!</p>
    <%= link "Setup custom backend", to: Routes.user_path(@conn, :edit) <> "#bigquery-backend", class: "btn btn-primary form-button", role: "button" %>
  <% end %>

  <%= section_header("Backend Clustering") %>
  <p>Set additional clustering columns to improve query performance. <code>timestamp</code> and <code>id</code> are always clustered.</p>
  <%= form_for @changeset, Routes.source_path(@conn, :update, @source), fn e -> %>
  <div class="form-group">
    <%= text_input e, :bigquery_clustering_fields, placeholder: "my_field,my_other_field", class: "form-control form-control-margin" %>
    <%= error_tag e, :bigquery_clustering_fields %>
    <small class="form-text text-muted">
      Comma-separated. For example: <code>my_field,my_other_field</code>.
    </small>
  </div>
  <%= submit "Update clustering", class: "btn btn-primary form-button" %>
  <% end %>

  <%= section_header("Suggested Search Keys") %>
  <p>Set suggested search keys for this source, to encourage usage of certain filtering keys when performing searches across large sources. If a declared key is missing, users will be prompted to include the key when a search is made.</p>
  <%= form_for @changeset, Routes.source_path(@conn, :update, @source),fn f -> %>
    <div class="form-group">
      <%= text_input f, :suggested_keys , class: "form-control form-control-margin" %>
      <%= error_tag f, :suggested_keys %>
    <small class="form-text text-muted">
      Comma-separated. For example: <code>status,metadata.level</code>. Add an exclaimation mark (!) to make the key required  <code>metadata.level!</code>
    </small>
    </div>
    <%= submit "Save", class: "btn btn-primary form-button" %>
  <% end %>


  <%= if @user.system_monitoring do %>
    <%= section_header("Monitoring Labels") %>
    <p>Set labels for this source, to be used for monitoring. Labels are used to group metrics together when system monitoring is enabled. Values of the labels will be determined at ingest time.</p>
    <%= form_for @changeset, Routes.source_path(@conn, :update, @source),fn f -> %>
      <div class="form-group">
        <%= text_input f, :labels , class: "form-control form-control-margin" %>
        <%= error_tag f, :labels %>
      <small class="form-text text-muted">
        Comma-separated. For example: <code>status=m.level,my_project=project.name</code>.
      </small>
      </div>
      <%= submit "Save", class: "btn btn-primary form-button" %>
    <% end %>
  <% end %>

  <%= section_header("Search Tailing") %>
  <%= form_for @changeset, Routes.source_path(@conn, :update, @source),fn f -> %>
    <div class="form-group">
      <%= label f, :disable_tailing do %>
        Toggle Source search tailing for this source. Currently <%= if(@source.disable_tailing, do: "disabled", else: "enabled") %>.
      <% end %>
      <%= hidden_input f, :disable_tailing, value: !@source.disable_tailing %>
    </div>

    <%= submit if(@source.disable_tailing, do: "Enable search tailing", else: "Disable search tailing"), class: "btn btn-primary form-button" %>
  <% end %>

  <%= if LogflareWeb.Utils.flag("multibackend", @user) == true do %>
     <%= section_header("Storage Write API Ingestion") %>
    <%= form_for @changeset, Routes.source_path(@conn, :update, @source),fn f -> %>
      <div class="form-group">
        <%= @source.bq_storage_write_api %>
        <%= label f, :bq_storage_write_api do %>
          Toggle storage write API BigQuery ingestion for this source
        <% end %>
        <%= checkbox f, :bq_storage_write_api, checked: @source.bq_storage_write_api, value: @source.bq_storage_write_api  %>
        <%= error_tag f, :bq_storage_write_api %>
      </div>
      <%= submit "Save", class: "btn btn-primary form-button" %>

    <% end %>

    <%= section_header("Multi Backends") %>
    <%= form_for @changeset, Routes.source_path(@conn, :update, @source),fn f -> %>
      <div class="form-group">
        <%= label f, :default_ingest_backend_enabled? do %>
          Toggle Default Ingest Mode
        <% end %>
        <%= checkbox f, :default_ingest_backend_enabled?, checked: @source.default_ingest_backend_enabled?, value: @source.default_ingest_backend_enabled?  %>
        <%= error_tag f, :default_ingest_backend_enabled? %>
      </div>

      <%= submit "Save", class: "btn btn-primary form-button" %>
    <% end %>
    <%= if LogflareWeb.Utils.flag("multibackend", @user) do %>
      <%= live_render(@conn, LogflareWeb.SourceBackendsLive, session: %{"source_id"=> @source.id})%>
    <% end %>

  <% end %>

  <%= section_header("Delete Source") %>
  <%= form_for @changeset, Routes.source_path(@conn, :delete, @source), [method: :delete], fn _f -> %>
    <%= submit class: "btn btn-outline-danger form-button", data: [confirm: "Are you sure? This cannot be undone"] do %>
      <i class="fas fa-trash"></i>
      Delete Source
    <% end %>
  <% end %>

  <script>
    document.addEventListener("DOMContentLoaded", async () => {
      const clipboard = new ClipboardJS('#copy-path')
      clipboard.on('success', (e) => {
        alert("Copied!");
        e.clearSelection();
      });

      clipboard.on('error', (e) => {
        alert("Something went wrong!");
        e.clearSelection();
      })
    })

  </script>
